/*******************************************************************************
 * Copyright (c) 2011 EclipseDevX.org and others.
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at:
 * 
 *     http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipsedevx.core.workspace;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipsedevx.core.DevXCorePlugin;

/**
 * 
 * 
 * @author dcarew
 */
public class ChangeListenersManager {
	private static final String EXT_ID = "org.eclipsedevx.core.workspaceChangeListener";
	
	private static ChangeListenersManager manager;
	
	private List<IWorkspaceChangeListener> listeners;
	
	private ChangeListenersManager() {
		discoverListeners();
	}
	
	public static List<IWorkspaceChangeListener> getListeners() {
		if (manager == null) {
			manager = new ChangeListenersManager();
		}
		
		return manager.getListenersImpl();
	}
	
	private List<IWorkspaceChangeListener> getListenersImpl() {
		return Collections.unmodifiableList(listeners);
	}

	private void discoverListeners() {
		listeners = new ArrayList<IWorkspaceChangeListener>();
		
		IConfigurationElement[] config = Platform.getExtensionRegistry()
			.getConfigurationElementsFor(EXT_ID);
		
		try {
			for (IConfigurationElement e : config) {
				final Object o = e.createExecutableExtension("class");
				
				if (o instanceof IWorkspaceChangeListener) {
					listeners.add((IWorkspaceChangeListener)o);
				}
			}
		} catch (CoreException ex) {
			DevXCorePlugin.logError(ex);
		}
	}
	
}
